﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace StudentStatistics
{
    public class AminationHelpers
    {
        DoubleAnimation xAnimation = new DoubleAnimation();
        Storyboard story = new Storyboard();

        /// <summary>
        /// usercontrol 必须在xaml中标识了 x:Name
        /// </summary>
        /// <param name="usercontrol"></param>
        public void SetAmination(FrameworkElement usercontrol, PropertyPath pp, double from, double to)
        {
            NameScope.SetNameScope(usercontrol, new NameScope());
            usercontrol.RegisterName(usercontrol.Name, usercontrol);
            xAnimation.From = from;
            xAnimation.To = to;
            xAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            story.AutoReverse = false;
            story.RepeatBehavior = new RepeatBehavior(1);
            story.Children.Add(xAnimation);
            Storyboard.SetTargetName(xAnimation, usercontrol.Name);
            Storyboard.SetTargetProperty(xAnimation, pp);
            story.Begin(usercontrol);
        }

        DispatcherTimer timer;
        ObservableCollection<Info> animationitems = new ObservableCollection<Info>();
        ObservableCollection<Info> viewItems = new ObservableCollection<Info>();
        /// <summary>
        /// 设置柱状图动画
        /// </summary>
        /// <param name="viewitems 中转集合"></param>
        /// <param name="items 绑定的集合"></param>
        public void SetViewAnimation(ObservableCollection<Info> items, ObservableCollection<Info> viewitems)
        {
            CloseTimer();

            viewitems.Clear();
            viewItems = viewitems;
            animationitems = items;
            StartTime();
        }

        private void StartTime()
        {
            CloseTimer();
            count = 0;
            timer = new System.Windows.Threading.DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 0, 0, 150);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        private void CloseTimer()
        {
            if (timer != null)
            {
                timer.Tick -= timer_Tick;
                timer.Stop();
                timer = null;
            }
        }

        int count = 0;
        public void timer_Tick(object sender, EventArgs e)
        {
            if (count >= animationitems.Count)
            {
                CloseTimer();
                return;
            }

            viewItems.Add(animationitems[count]);
            count++;
        }

        ~AminationHelpers()
        {
            animationitems = new ObservableCollection<Info>();
            viewItems = new ObservableCollection<Info>();
            CloseTimer();
        }

    }
}
